import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {
  Badge,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Icon,
  Input,
  InputNumber,
  Modal,
  Radio,
  Row,
  Select,
  Table,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../search.less';

const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;
const InputGroup = Input.Group;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');
const relationMap = [' ', ' '];
const relation = ['与', '或'];
const statusMap = ['success ', 'error '];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};
const reduceStyle = {
  position: 'absolute',
  right: 0,
  top: '5px',
}

@Form.create()


class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {
    },
    handleUpdateModalVisible: () => {
    },
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      mapTime: [],
      mapSensitiveRulePoList: this.props.values.sensitiveRulePoList,
    }
  }

  okHandle = () => {
    const {
      values,
      form,
      handleUpdate
    } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleUpdate(values, fieldsValue);
    });
  };
  plusData = () => {
    const {mapTime} = this.state;
    this.setState({
      mapTime: [...mapTime, 1]
    })
  }
  reduceData = (index) => {
    const {mapTime} = this.state;
    const copyMapTime = [...mapTime];
    copyMapTime.splice(index, 1)
    this.setState({
      mapTime: copyMapTime,
    })
  }
  reduceDataT = (index) => {
    const {mapSensitiveRulePoList} = this.state;
    const copyMapSensitiveRulePoList = [...mapSensitiveRulePoList];
    copyMapSensitiveRulePoList.splice(index, 1)
    this.setState({
      mapSensitiveRulePoList: copyMapSensitiveRulePoList,
    })
  }


  render() {
    const {
      updateModalVisible,
      handleUpdateModalVisible,
      values,
      form,
      form: {getFieldDecorator},
      sensitiveWordsList,
    } = this.props;
    const {mapTime, mapSensitiveRulePoList} = this.state;
    return (
      <Modal
        width={800}
        bodyStyle={{padding: '32px 40px 48px'}}
        destroyOnClose
        title="编辑敏感等级"
        visible={updateModalVisible}
        maskClosable={false}
        footer={[
          <Button key="back" onClick={() => handleUpdateModalVisible(false, values)}>取消</Button>,
          <Button type="primary" htmlType="submit" key="primary" onClick={this.okHandle}>确定</Button>
        ]}
        onCancel={() => handleUpdateModalVisible(false, values)}
      >
        <Form>
          <Row gutter={16}>
            <Col md={12}>
              <FormItem {...formLayout} label="等级名称">
                {form.getFieldDecorator('name', {
                  rules: [{required: true, message: '等级名称不能为空'}], initialValue: values.name
                })(<Input placeholder="请输入"/>)}
              </FormItem>
            </Col>

            <Col md={12}>
              <FormItem {...formLayout} label="等级">
                {form.getFieldDecorator('sensitiveLevel', {
                  rules: [{required: true, message: '请选择等级'}], initialValue: values.sensitiveLevel
                })(<Select disabled placeholder="请选择">
                  <Option value="0">0</Option>
                  <Option value="1">1</Option>
                  <Option value="2">2</Option>
                  <Option value="3">3</Option>
                  <Option value="4">4</Option>
                </Select>)}
              </FormItem>
            </Col>
            <Col md={12}>
              <FormItem {...formLayout} label="关系">
                {form.getFieldDecorator('sensitiveRel', {
                  rules: [{required: true, message: '请选择关系'}],
                  initialValue: values.sensitiveRel
                })(
                  <Radio.Group>
                    <Radio value={0}>
                      与
                    </Radio>
                    <Radio value={1}>
                      或
                    </Radio>
                  </Radio.Group>
                )}
              </FormItem>
            </Col>

            <Col md={12}>
              <FormItem {...formLayout} label="状态" style={{display: values == null ? 'none' : 'block',}}>
                {form.getFieldDecorator('sensitiveState', {
                  initialValue: values && values.sensitiveState
                })(
                  <Radio.Group>
                    <Radio value={0}>
                      启用
                    </Radio>
                    <Radio value={1}>
                      禁用
                    </Radio>
                  </Radio.Group>
                )}
              </FormItem>
            </Col>
            {/*  <div style={{clear:'both'}}></div>*/}

            {
              mapSensitiveRulePoList.map((v, i) => {
                return (
                  <Fragment key={i}>
                    <Col md={12}>
                      <FormItem {...formLayout} label="敏感字段">
                        {form.getFieldDecorator('sensitiveRuleCreateFormList[' + i + '].wordId', {
                          rules: [{required: true, message: '敏感字段不能为空'}],
                          initialValue: v.wordId
                        })(<Select placeholder="请选择">
                          {
                            sensitiveWordsList.map((item, index) => {
                              return (<Option key={item.id} value={item.id}>{item.name}</Option>)
                            })
                          }
                        </Select>)}
                      </FormItem>
                      <FormItem {...formLayout} label="id" style={{display: 'none'}}>
                        {form.getFieldDecorator('sensitiveRuleCreateFormList[' + i + '].id', {
                          initialValue: v.id
                        })(<Input placeholder="请输入"/>)}
                      </FormItem>
                    </Col>

                    <Col md={12}>
                      <FormItem {...formLayout} label="出现次数">
                        <InputGroup>
                          {getFieldDecorator('sensitiveRuleCreateFormList[' + i + '].minTimes', {
                            rules: [{
                              required: false,
                              message: '请输入次数'
                            }], initialValue: v.minTimes
                          })(
                            <InputNumber min={0} max={99999999} style={{width: '100px'}}/>
                          )}
                          <span>&nbsp;~&nbsp;</span>
                          {getFieldDecorator('sensitiveRuleCreateFormList[' + i + '].maxTimes', {
                            rules: [{
                              required: false,
                              message: '请输入次数'
                            }], initialValue: v.maxTimes
                          })(
                            <InputNumber min={0} max={99999999} style={{width: '100px'}}/>
                          )}
                        </InputGroup>
                        <a style={{color: '#f5222d'}}>
                          <Icon style={reduceStyle} type="close-circle" onClick={() => this.reduceDataT(i)}/>
                        </a>
                      </FormItem>
                    </Col>
                  </Fragment>
                )
              })
            }
            {
              mapTime.map((v, i) => {
                return (
                  <Fragment key={mapSensitiveRulePoList.length + i}>
                    <Col md={12}>
                      <FormItem {...formLayout} label="敏感字段">
                        {form.getFieldDecorator('sensitiveRuleCreateFormList[' + (mapSensitiveRulePoList.length + i) + '].wordId', {
                          rules: [{required: true, message: '敏感字段不能为空'}],
                        })(<Select placeholder="请选择">
                          {
                            sensitiveWordsList.map((item, index) => {
                              return (<Option key={item.id} value={item.id}>{item.name}</Option>)
                            })
                          }
                        </Select>)}
                      </FormItem>
                    </Col>
                    <Col md={12}>
                      <FormItem {...formLayout} label="出现次数">
                        <InputGroup>
                          {getFieldDecorator('sensitiveRuleCreateFormList[' + (mapSensitiveRulePoList.length + i) + '].minTimes', {
                            rules: [{
                              required: false,
                              message: '请输入次数'
                            }], initialValue: 0
                          })(
                            <InputNumber min={0} max={99999999} style={{width: '100px'}}/>
                          )}
                          <span>&nbsp;~&nbsp;</span>
                          {getFieldDecorator('sensitiveRuleCreateFormList[' + (mapSensitiveRulePoList.length + i) + '].maxTimes', {
                            rules: [{
                              required: false,
                              message: '请输入次数'
                            }], initialValue: 0
                          })(
                            <InputNumber min={0} max={99999999} style={{width: '100px'}}/>
                          )}
                        </InputGroup>
                        <a style={{color: '#f5222d'}}>
                          <Icon style={reduceStyle} type="close-circle" onClick={() => this.reduceData(i)}/>
                        </a>
                      </FormItem>
                    </Col>

                  </Fragment>
                )
              })
            }
            <Col md={24}>
              <Button type="dashed" onClick={this.plusData} block><Icon type="plus"/>新增</Button>
            </Col>
          </Row>
        </Form>

      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({level, loading}) => ({
  level,
  loading: loading.models.level,
}))
@Form.create()
class level extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    editFormValues: {},
    isDetail: false,
    deatilsData: {},
    sensitiveWordsList: [], // 敏感字段
  };

  // 将数组对象的值转化为字符串显示
  arrayToString = (data = [], key) => {
    let str = '';
    data.map(function (v, i) {
      let newValue = v[key] ? v[key] : ' '
      if (data.length - 1 == i) {
        str = str + newValue;
      } else {
        str = str + newValue + ',';
      }
    });
    return str
  };


  columns = [
    {
      title: '等级名称',
      dataIndex: 'name',
    },
    {
      title: '等级',
      dataIndex: 'sensitiveLevel',
    },
    {
      title: '敏感字段',
      render: (text, record) => (
        <span>{this.arrayToString(text.sensitiveRulePoList, 'sensitiveWordName')}</span>
      ),

    },
    {
      title: '关系',
      dataIndex: 'sensitiveRel',
      render(val) {
        return <Badge status={relationMap[val]} text={relation[val]}/>;
      },
    },
    {
      title: '状态',
      dataIndex: 'sensitiveState',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.openDetailsPage(true, text)}>详情</a>
          <Divider type="vertical"/>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
        </Fragment>
      ),
    },
  ];

  openDetailsPage = (flag, res) => {
    this.setState({
      isDetail: true,
      deatilsData: res,
    });
  };

  componentDidMount() {
    this.pageList();
    this.WordsList();//敏感字段

  }

  // 分页查询列表
  pageList(pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'level/queryList',
      payload: values,
    });
  }

  WordsList = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'level/sensitiveWordsList',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            sensitiveWordsList: res.data.dataList,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };


  handleStandardTableChange = (pagination, filters, sorter) => {
    // 分页请求
    this.pageList(pagination.pageSize, pagination.current - 1);
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      editFormValues: record || {},
    });
  };

  handleIsDetails = (flag) => {
    this.setState({
      isDetail: !!flag,
    });
  };

  //验证--++--编辑
  handleUpdate = (values, fields) => {
    const {dispatch} = this.props;
    let obj = {};
    fields.sensitiveRuleCreateFormList && fields.sensitiveRuleCreateFormList.map((v, i) => {
      let maxTimes = 'sensitiveRuleCreateFormList[' + i + '].maxTimes';
      let minTimes = 'sensitiveRuleCreateFormList[' + i + '].minTimes';
      let wordId = 'sensitiveRuleCreateFormList[' + i + '].wordId';
      let id = 'sensitiveRuleCreateFormList[' + i + '].id';
      obj[maxTimes] = v.maxTimes||0;
      obj[minTimes] = v.minTimes||0;
      obj[wordId] = v.wordId;
      obj[id] = v.id || '';
    });
    const parmas = {
      id: values.id,
      name: fields.name,
      sensitiveLevel: fields.sensitiveLevel,
      sensitiveRel: fields.sensitiveRel,
      sensitiveState: fields.sensitiveState,
    }
    const assignObj = Object.assign(obj, parmas);
    dispatch({
      type: 'level/checkRule',
      payload: assignObj,
      callback: (res) => {
        if (res.result == "ok") {
          this.handleUpdateModalVisible();
          this.handleCheckUpdata(assignObj);
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      }
    });

  };

  handleCheckUpdata = (assignObj) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'level/update',
      payload: assignObj,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  render() {
    const {
      level: {data},
      loading,
    } = this.props;
    const {selectedRows, modalVisible, updateModalVisible, editFormValues, isDetail, deatilsData, sensitiveWordsList} = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    const detailMethods = {
      handleIsDetails: this.handleIsDetails,
    };

    return (
      <PageHeaderWrapper title="敏感等级">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              hideRowSelection={true}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey={record => record.id}
            />
          </div>
          <DetailPage
            {...detailMethods}
            isDetail={isDetail}
            deatilsData={deatilsData}
          />

          {editFormValues && Object.keys(editFormValues).length && updateModalVisible ? (
            <UpdateForm
              {...updateMethods}
              updateModalVisible={updateModalVisible}
              values={editFormValues}
              sensitiveWordsList={sensitiveWordsList}
            />
          ) : null}

        </Card>
      </PageHeaderWrapper>
    );
  }
}

class DetailPage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  renderFooter = () => {
    const {handleIsDetails} = this.props;
    return [
      <Button key="forward" type="primary" onClick={() => handleIsDetails(false)}>
        返回
      </Button>,
    ];
  };

  render() {
    const {handleIsDetails, deatilsData, isDetail} = this.props;
    const columns = [
      {
        title: '敏感字段名称',
        dataIndex: 'sensitiveWordName',
      },
      {
        title: '最少次数',
        dataIndex: 'minTimes',

      },
      {
        title: '最多次数',
        dataIndex: 'maxTimes',

      },
    ];
    const data = deatilsData.sensitiveRulePoList;
    return (
      <Modal
        width={800}
        bodyStyle={{padding: '32px 40px 48px'}}
        destroyOnClose
        title="敏感等级详情"
        visible={isDetail}
        footer={this.renderFooter()}
        onCancel={() => handleIsDetails(false)}
      >
        <Row gutter={16}>
          <Col md={12}>
            <FormItem {...formLayout} label="等级名称">
              <div>{deatilsData.name}</div>
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="等级">
              <div>{deatilsData.sensitiveLevel}</div>
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="状态">
              <div>{status[deatilsData.sensitiveState]}</div>
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="关系">
              <div>{relation[deatilsData.sensitiveRel]}</div>
            </FormItem>
          </Col>
        </Row>
        <Table columns={columns} dataSource={data}/>
      </Modal>
    );
  }
}

export default level;
